package org.lim.lcpicturebackend.manager.upload;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.lim.lcpicturebackend.config.OssClientConfig;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@Component
@Slf4j
public class CosManager {

    @Resource
    private OssClientConfig ossClientConfig;

    @Resource
    private OSS ossClient;

    /**
     * 上传对象
     *
     * @param key  唯一键
     * @param file 文件
     */
    public PutObjectResult putObject(String key, File file) {
        // 验证参数
        if (StringUtils.isBlank(key)) {
            throw new IllegalArgumentException("上传key不能为空");
        }
        if (file == null || !file.exists()) {
            throw new IllegalArgumentException("上传文件不存在");
        }

        try {
            // 确保key不以斜杠开头，这是阿里云OSS的要求
            String cleanKey = key;
            if (cleanKey.startsWith("/")) {
                cleanKey = cleanKey.substring(1);
                log.info("Removed leading slash from key: {} -> {}", key, cleanKey);
            }

            // 验证清理后的key
            if (StringUtils.isBlank(cleanKey)) {
                throw new IllegalArgumentException("处理后的key不能为空");
            }

            log.info("Uploading file to OSS - bucket: {}, key: {}, file size: {}",
                    ossClientConfig.getBucket(), cleanKey, file.length());

            PutObjectRequest putObjectRequest = new PutObjectRequest(
                    ossClientConfig.getBucket(),
                    cleanKey,
                    new FileInputStream(file)
            );

            PutObjectResult result = ossClient.putObject(putObjectRequest);
            log.info("Upload successful - ETag: {}, RequestId: {}",
                    result.getETag(), result.getRequestId());

            return result;
        } catch (IOException e) {
            log.error("Failed to read file for upload: {}", file.getAbsolutePath(), e);
            throw new RuntimeException("读取上传文件失败: " + e.getMessage(), e);
        } catch (Exception e) {
            log.error("Failed to upload file to OSS - key: {}, error: {}", key, e.getMessage(), e);
            throw new RuntimeException("上传文件到OSS失败: " + e.getMessage(), e);
        }
    }

    /**
     * 上传对象（附带图片信息）
     * 注意：阿里云OSS不像腾讯云COS那样在上传时直接返回图片信息
     * 这里保持接口一致性，实际的图片信息处理在FileManager中完成
     *
     * @param key  唯一键
     * @param file 文件
     */
    public PutObjectResult putPictureObject(String key, File file) {
        return putObject(key, file);
    }

    public String getBaseUrl() {
        // 阿里云OSS的访问地址格式：https://bucket-name.endpoint
        String baseUrl = String.format("https://%s.%s", ossClientConfig.getBucket(), ossClientConfig.getEndpoint());
        log.debug("Generated base URL: {}", baseUrl);
        return baseUrl;
    }
    public void deleteObject(String key) {
        try {
            ossClient.deleteObject(ossClientConfig.getBucket(), key);
            log.info("对象成功从对象存储删除 - bucket: {}, key: {}", ossClientConfig.getBucket(), key);        } catch (Exception e) {
            log.error("删除失败 - key: {}, error: {}", key, e.getMessage(), e);
            throw new RuntimeException("删除对象失败: " + e.getMessage(), e);
        }
    }
}